package com.sgb.member.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.material.tabs.TabLayout;
import com.sgb.member.MemberConfig;
import com.sgb.member.PickCateType;
import com.sgb.member.R;
import com.sgb.member.databinding.FragmentMemberLogistics2Binding;
import com.sgb.member.di.DaggerMemberFragComponent;
import com.sgb.member.di.MemberFragModule;
import com.sgb.member.entity.MemberCheckStateEntity;
import com.sgb.member.entity.MemberLogisticsEntity;
import com.sgb.member.ui.adapter.WuLiuMemberAdapter2;
import com.sgb.member.view_model.BusinessLogisticsMode2;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.XCustomTabLayout;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.CopyUtils;
import com.swgk.core.view.selection.MemberStatusView;
import com.swgk.core.view.selection.XChooseDialog;
import com.swgk.core.view.selection.XChooseEntity;
import com.swgk.core.xrecyclerview.LoadingMoreFooter;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 会员经营-物流货运-会员货运
 */
public class BusinessLogisticsFragment2 extends AppLazyFragment implements MemberStatusView.OnChooseListener, XChooseDialog.DialogCallBackImpl {

    @Inject
    public BusinessLogisticsMode2 sModel;
    private FragmentMemberLogistics2Binding mBinding;
    private WuLiuMemberAdapter2<MemberLogisticsEntity> mAdapter;
    private CommonPopEntity mEntity; // 主页面TAB下标

    // 经营地址Popup
    private ThreeLevelAreaWindow mStartAddressPop;
    private ThreeLevelAreaWindow mEndAddressPop;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;
    private String oneLevel = "";
    private String twoLevel = "";

    private String mNo1;
    private String loadingTime=""; // 装货时间
    private GoodsSourceLocationEntity mStartEntity; // 装货地
    private GoodsSourceLocationEntity mEndEntity; // 目的地

    private List<CommonPopEntity> mCarTypeAndLens;
    private String member_level = "";//会员等级
    private List<CommonPopEntity> list = new ArrayList<>();

    public static BusinessLogisticsFragment2 newInstance() {
        BusinessLogisticsFragment2 fragment = new BusinessLogisticsFragment2();
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMemberFragComponent.builder()
                .appComponent(appComponent)
                .memberFragModule(new MemberFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_member_logistics_2, container, false);
        mBinding.setLifecycleOwner(this);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        initRecycler();
        initPopup();
        initChooseDialog();
        mBinding.chooseLayout.setOnClickListener(v -> {
            mChooseDialog.initData(mData, mFilters);
            mChooseDialog.showDialog();
        });
        loadOtherData();
    }

    @Override
    protected void onLazyLoad() {
        oneLevel = "";
        twoLevel="";
        sModel.getLogisticsType();
        loadData(false);
    }

    public void loadData(boolean isLoadMore) {
        sModel.getFilterSourceList( isLoadMore, oneLevel, twoLevel, mNo1,
               loadingTime, mStartEntity, mEndEntity, member_level);

    }

    public void loadOtherData() {
        if (scrData == null) {
            sModel.getAddressModel();
        }
        if (isListEmpty(PickCateType.TYPE_1)) {
            sModel.getWeight();
        }
        if (isListEmpty(PickCateType.TYPE_6)) {
            sModel.getMemberLevelData(); // 会员级别
        }
    }

    public void setAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        scrData = data;
        mStartEntity = new GoodsSourceLocationEntity();
        mEndEntity = new GoodsSourceLocationEntity();
        mStartAddressPop.setData(scrData, true);
        mEndAddressPop.setData(scrData, true);
    }

    public void setOneTabType(List<CommonPopEntity> dates) {
        this.list.clear();
        this.list.addAll(dates);
        mBinding.childTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        mBinding.childTabLayout.setVisibility(View.VISIBLE);
        for (int i = 0; i < list.size(); i++) {
            mBinding.childTabLayout.addTab(mBinding.childTabLayout.newTab().setText(list.get(i).getTypeName()));
        }
        mBinding.childTabLayout.setNormalColor(R.color.color_title_small);
        mBinding.childTabLayout.addOnTabSelectedListener(list, new XCustomTabLayout.SimpleSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int pos = tab.getPosition();
                mEntity = list.get(pos);
                oneLevel = list.get(pos).getNo();
                twoLevel = "";
                setSecondTabType(mEntity.getChildren());
                loadData(false);
            }
        });
    }

    private List<CommonPopEntity> secondTabDatas = new ArrayList<>();

    public void setSecondTabType(List<CommonPopEntity> list) {
        if (list == null || list.size() == 0) {
            mBinding.secondChildTabLayout.setVisibility(View.GONE);
            return;
        }
        secondTabDatas.clear();
        secondTabDatas.add(0, new CommonPopEntity("", "全部"));
        secondTabDatas.addAll(list);
        mBinding.secondChildTabLayout.setVisibility(View.VISIBLE);
        mBinding.secondChildTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        mBinding.secondChildTabLayout.removeAllTabs();
        mBinding.secondChildTabLayout.setOnTabSelectedListener(null);
        for (int i = 0; i < secondTabDatas.size(); i++) {
            mBinding.secondChildTabLayout.addTab(mBinding.secondChildTabLayout.newTab().setText(secondTabDatas.get(i).getTypeName()));
        }
        mBinding.secondChildTabLayout.setNormalColor(R.color.color_title_small);
        mBinding.secondChildTabLayout.addOnTabSelectedListener(secondTabDatas, new XCustomTabLayout.SimpleSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int pos = tab.getPosition();
                twoLevel = secondTabDatas.get(pos).getNo();
                loadData(false);
            }
        });
    }

    // 更新货物重量（吨）
    public void setWeightData(List<CommonPopEntity> list) {
        addMainEntity(PickCateType.TYPE_1, list);
    }

    public void setMemberLevelData(List<CommonPopEntity> list) {
        addMainEntity(PickCateType.TYPE_6, list);
    }

    // 更新装货时间
    public void setTimeData(List<CommonPopEntity> list) {
        mBinding.popLoadTime.setData(list);
        mBinding.popLoadTime.showPop();
    }

    /**
     * -------------------------------------initRecycler------------------------------------------
     */
    private void initRecycler() {
        TextView textView = mBinding.emptyView.findViewById(R.id.no_data_count);
        textView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setPullRefreshEnabled(true);
        mBinding.recyclerView.setLoadingMoreEnabled(true);
        LoadingMoreFooter footer = (LoadingMoreFooter) mBinding.recyclerView.getFootView();
        footer.setNoMoreHint("已经到底啦~");
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(false);
            }

            @Override
            public void onLoadMore() {
                loadData(true);
            }
        });
        mAdapter = new WuLiuMemberAdapter2(getActivity(), R.layout.item_other_logistics_2, null);
        mAdapter.setOnItemClick(new AdapterOnItemClick<MemberLogisticsEntity>() {
            @Override
            public void onItemClick(MemberLogisticsEntity goodsListEntity, int position) {
                if (null != mAdapter && mAdapter.getDatas().size() > 0) {
                    sModel.goodsSourceStatusCheck(goodsListEntity.getNo(), position);
                }
            }
        });
        mBinding.recyclerView.setAdapter(mAdapter);
    }

    public void checkGoodsState(int position, MemberCheckStateEntity stateEntity) {
        if (stateEntity.goodsIsGone()) {
            new RoundDialog.Builder(getActivity())
                    .title("提示")
                    .content("该货源不存在，请选择其他货源接单")
                    .singleBtn(true)
                    .confirm("知道了")
                    .confirmCallback(v -> {
                        mAdapter.getDatas().remove(position);
                        mAdapter.notifyDataSetChanged();
                    })
                    .show();
        } else if (stateEntity.goodsIsReceipted()) {
            new RoundDialog.Builder(getActivity())
                    .title("提示")
                    .content("该货源已被接单，请选择其他货源接单")
                    .singleBtn(true)
                    .confirm("知道了")
                    .confirmCallback(v -> {
                        mAdapter.getDatas().remove(position);
                        mAdapter.notifyDataSetChanged();
                    })
                    .show();

        } else {
            if (null != mAdapter && mAdapter.getDatas().size() > 0) {
                if (mAdapter.getDatas().get(position).getPattern() == 1) {
                    MemberConfig.getInstance().startFreightPrjDetailActivity(getActivity(), mAdapter.getDatas().get(position).getNo(), false, false);
                } else {
                    MemberConfig.getInstance().startGeneralPrjDetailActivity(getActivity(), mAdapter.getDatas().get(position).getNo(), mAdapter.getDatas().get(position).getPattern(), false);
                }
            }
        }
    }

    public void closeRecyclerRefreshing() {
        mBinding.recyclerView.refreshComplete();
        mBinding.recyclerView.loadMoreComplete();
    }

    public void showEmpty() {
        closeRecyclerRefreshing();
        mAdapter.clearDatas();
        mBinding.emptyView.setVisibility(View.VISIBLE);
    }

    public void refreshRecycler(List<MemberLogisticsEntity> list, boolean isLoadMore, boolean noMoreData) {
        mBinding.recyclerView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setNoMore(noMoreData);
        closeRecyclerRefreshing();
        if (isLoadMore) {
            if (list != null && list.size() > 0) {
                mAdapter.addDatas(list);
            }
        } else {
            if (list != null && list.size() > 0) {
                mBinding.emptyView.setVisibility(View.GONE);
                mAdapter.setDatas(list);
            } else {
                mAdapter.clearDatas();
                mBinding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * ------------------------------- Popup ---------------------------------------------
     */
    private void initPopup() {
        mStartEntity = new GoodsSourceLocationEntity();
        mEndEntity = new GoodsSourceLocationEntity();
        mBinding.popStartAddress.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popEndAddress.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popLoadTime.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mStartAddressPop = initAddressPopup(mBinding.popStartAddress);
        mEndAddressPop = initAddressPopup(mBinding.popEndAddress);
    }

    @Override
    public void onLoadChooseData(String mKeyName) {
        if ("装货时间".equals(mKeyName)) {
            sModel.getTimeData();
        }
    }

    @Override
    public void onChooseResult(String mKeyName, CommonPopEntity entity, Object... objects) {
        int position = (int) objects[0];
        String no = position == 0 ? "" : entity.getNo();
        if ("装货时间".equals(mKeyName)) {
            if (!TextUtils.equals(no, loadingTime)) {
                loadingTime = entity.getNo();
                loadData(false);
            }
        }
    }

    private ThreeLevelAreaWindow initAddressPopup(MemberStatusView statusView) {
        ThreeLevelAreaWindow mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(mBinding.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setAreaSingle();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(false);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(false);
        mAddressPop.setSecondaryListIsGone(false);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                statusView.updateChooseTextStatus(0, statusView.getKeyName());
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    statusView.updateChooseTextStatus(1, entity.getProvinceName());
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        statusView.updateChooseTextStatus(1, entity.getCityName());
                        if (!TextUtils.isEmpty(entity.getAreaNo())) {
                            statusView.updateChooseTextStatus(1, entity.getAreaName());
                        }
                    }
                }
                switch (statusView.getKeyName()) {
                    case "装货地":
                        mStartEntity = entity;
                        break;
                    case "目的地":
                        mEndEntity = entity;
                        break;
                }
                //刷新数据
                loadData(false);
            }
        });
        mAddressPop.setOnDismissListener(() -> {
            mBinding.popLine.setVisibility(View.GONE);
            GoodsSourceLocationEntity temEntity = null;
            switch (statusView.getKeyName()) {
                case "装货地":
                    temEntity = mStartEntity;
                    break;
                case "目的地":
                    temEntity = mEndEntity;
                    break;
            }
            if (temEntity != null) {
                if (!TextUtils.isEmpty(temEntity.getProvinceNo())) {
                    statusView.updateChooseTextStatus(1, null);
                } else {
                    statusView.updateChooseTextStatus(0, statusView.getKeyName());
                }
            } else {
                statusView.updateChooseTextStatus(0, statusView.getKeyName());
            }
        });
        statusView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (scrData == null) {
                    sModel.getAddressModel();
                    return;
                }
                mBinding.popLine.setVisibility(View.GONE);
                GoodsSourceLocationEntity temEntity = null;
                switch (statusView.getKeyName()) {
                    case "装货地":
                        temEntity = mStartEntity;
                        break;
                    case "目的地":
                        temEntity = mEndEntity;
                        break;
                }
                if (temEntity != null) {
                    if (!TextUtils.isEmpty(temEntity.getProvinceNo())) {
                        statusView.updateChooseTextStatus(1, null);
                    } else {
                        statusView.updateChooseTextStatus(0, statusView.getKeyName());
                    }
                } else {
                    statusView.updateChooseTextStatus(0, statusView.getKeyName());
                }
                mAddressPop.showPopwindow0(mBinding.popLine);
            }
        });
        return mAddressPop;
    }

    /**
     * ------------------------------------ 侧滑刷选 ----------------------------------------
     */

    private XChooseDialog mChooseDialog;
    private SparseArray<XChooseEntity> mData = new SparseArray<>();
    // 本地缓存筛选结果
    private SparseIntArray mFilters = new SparseIntArray();
    private SparseArray<String> mNameArray;

    private void initChooseDialog() {
        mNameArray = new SparseArray<>();
        mNameArray.put(PickCateType.TYPE_1, "货物重量(吨)");
        mNameArray.put(PickCateType.TYPE_6, "会员等级");
        mChooseDialog = new XChooseDialog(getContext(), mNameArray);
        mChooseDialog.setCallBack(this);
        for (int i = 0; i < mNameArray.size(); i++) {
            int key = mNameArray.keyAt(i);
            addMainEntity(key, new ArrayList<>());
        }
    }

    public void showLeftDialog(int type, List<CommonPopEntity> data) {
        mChooseDialog.addEntity(type, data);
        mChooseDialog.showDialog();
    }

    public void addMainEntity(int index, List<CommonPopEntity> list) {
        if (mData.get(index) != null) {
            if (list == null || list.size() == 0) {
                mData.get(index).setList(new ArrayList<>());
            } else {
                mData.get(index).setList(list);
            }
        } else {
            mData.put(index, new XChooseEntity(index, mNameArray.get(index), list));
        }
    }

    private boolean isListEmpty(int catType) {
        return mData.get(catType) != null &&
                (mData.get(catType).getList() == null || mData.get(catType).getList().size() == 0);
    }

    @Override
    public void loadChildData(XChooseEntity entity, int pos) {
    }


    @Override
    public void result(SparseArray<XChooseEntity> data, SparseIntArray map) {
        mData = CopyUtils.deepPopEntityCopy(data);
        mFilters = map.clone();
        for (int i = 0; i < mData.size(); i++) {
            int key = mData.keyAt(i);
            refreshItemValue(key, mFilters.get(key));
        }
        loadData(false);
    }

    private void refreshItemValue(int key, int value) {
        XChooseEntity entity = mData.get(key);
        String itemNo = entity.getItemNo(value);
        switch (key) {
            case PickCateType.TYPE_1:
                mNo1 = itemNo;
                break;
            case PickCateType.TYPE_6:
                member_level = entity.getItemId(value);
                break;
            default:
                break;
        }
    }

    @Override
    public void reset() {
        mFilters.clear();
        result(mData, mFilters);
        mChooseDialog.initData(mData, mFilters);
        mChooseDialog.showDialog();
    }


    @Override
    public void onCancel() {
        mChooseDialog.initData(mData, mFilters);
    }
}
